#include <stdio.h>
#include "esp_log.h"
#include "driver/i2c.h"
#include "sdkconfig.h"

#define SDA_IO 18
#define SCL_IO 19
#define DEVICE_ADDRESS 0x38
#define REGISTER_ADDRESS 0x70






void read_lux_task(void *args)
{
    uint8_t *data_read=( uint8_t *)malloc(6);

    uint8_t *data_reset=(uint8_t *)malloc(2);
    data_reset[0]=112;
    data_reset[1]=186;

    uint8_t *data_inital=( uint8_t *)malloc(4);
    data_inital[0]=112;
    data_inital[1]=225;
    data_inital[2]=8;
    data_inital[3]=0;
    while (true)
    {
        i2c_cmd_handle_t  cmd=i2c_cmd_link_create();
        i2c_master_start(cmd);

        i2c_master_write_byte(cmd,DEVICE_ADDRESS<<1,1);
        i2c_master_write(cmd,data_reset,2,1);
        i2c_master_write(cmd,data_inital,4,1);

        i2c_master_read(cmd, data_read, 6,I2C_MASTER_ACK);

        i2c_master_stop(cmd);
        i2c_master_cmd_begin(0, cmd, 1000 / portTICK_RATE_MS);
        i2c_cmd_link_delete(cmd);

        int  value=(((data_read[0]& 0x0F)<<16|data_read[4] << 8 | data_read[5])/100000)*50;
        printf("%d\n",value);

        vTaskDelay(1000 / portTICK_RATE_MS);
    }
}

void app_main(void)
{



    i2c_config_t i2c_config = {
            .mode = I2C_MODE_MASTER,
            .sda_io_num = SDA_IO,
            .scl_io_num = SCL_IO,
            .sda_pullup_en = GPIO_PULLUP_ENABLE,
            .scl_pullup_en = GPIO_PULLUP_ENABLE,
            .master.clk_speed = 100000};

    i2c_param_config(I2C_NUM_0, &i2c_config);
    i2c_driver_install(I2C_NUM_0, I2C_MODE_MASTER, 0, 0, 0);




    xTaskCreate(&read_lux_task, "lux", 8000, NULL, 1, NULL);



}
